package cn.edu.scnu.service;

import com.easymall.common.utils.UploadUtil;
import com.easymall.common.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

@Service
public class PicService {
    @Value("${pic.pathDirPrefix}")
    private String pathDirPrefix;
    @Value("${pic.urlPrefix}")
    private String urlPreparePrefix;

    public PicUploadResult picUpload(MultipartFile pic) {
        PicUploadResult result = new PicUploadResult();
        String originName = pic.getOriginalFilename();
        String extName = originName.substring(originName.lastIndexOf("."));
        boolean isOk = extName.matches(".(jpg|png|gif|JPG|PNG|GIF)$");
        if (!isOk) {
            result.setError(1);
            return result;
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(pic.getInputStream());
            bufferedImage.getWidth();
            bufferedImage.getHeight();
        } catch (Exception e) {
            e.printStackTrace();
            result.setError(1);
            return result;
        }
        String dir = "/" + UploadUtil.getUploadPath(originName, "upload") + "/";
        String pathDir = pathDirPrefix + dir;
        File file = new File(pathDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String urlPrefix = urlPreparePrefix + dir;
        String fileName = UUID.randomUUID() + extName;
        try {
            pic.transferTo(new File(pathDir + fileName));
        } catch (Exception e) {
            e.printStackTrace();
            result.setError(1);
            return result;
        }
        result.setUrl(urlPrefix + fileName);
        return result;
    }
}
